package com.qst.order.controller;

import com.qst.order.domain.Notice;
import com.qst.order.service.NoticeService;
import com.qst.order.utils.JwtUtil;
import com.qst.order.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 通知控制器
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/merchant")
public class NoticeController {

    private final NoticeService noticeService;

    private final JwtUtil jwtUtil;
    @GetMapping("/notices")
    public Result<List<Notice>> getNotices(@RequestHeader("Authorization") String token) {

        Integer merchantId =Integer.valueOf(jwtUtil.getClaim(token, "userId")) ;
        // 查询该商家的所有通知
        List<Notice> notices = null;
        try {
            notices = noticeService.lambdaQuery().eq(Notice::getMerchantId, merchantId).list();
        } catch (Exception e) {
            log.error("查询通知失败", e);
            throw new RuntimeException(e);
        }
        return Result.success(notices);
    }
    
    @PostMapping("/notices/mark-all-read")
    @Transactional
    public Result<Void> markAllRead(@RequestHeader("Authorization") String token) {
        Integer merchantId =Integer.valueOf(jwtUtil.getClaim(token, "userId")) ;
        noticeService.lambdaUpdate().set(Notice::getIsRead, true).eq(Notice::getMerchantId, merchantId).update();
        return Result.success();
    }

    // 标记通知已读
    @PostMapping("/mark-read/{noticeId}")
    @Transactional
    public Result<Void> markNoticeRead(@PathVariable("noticeId")Integer noticeId,
                                       @RequestHeader("Authorization") String token) {
        // 关键：将String转换为Integer
        Integer merchantId = Integer.valueOf(jwtUtil.getClaim(token, "userId"));  // 转为Integer
        // 执行更新时，条件类型完全匹配
        boolean success = noticeService.lambdaUpdate()
                .set(Notice::getIsRead, true)
                .eq(Notice::getId, noticeId)  // id: Integer vs Integer
                .eq(Notice::getMerchantId, merchantId)  // merchantId: Integer vs Integer
                .update();

        // 增加更新结果校验
        if (!success) {
            log.warn("通知标记已读失败，noticeId:{}，merchantId:{}", noticeId, merchantId);
            return Result.error("标记已读失败");
        }
        return Result.success();
    }
}